﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UL360DataNET40;
using System.Reflection;

namespace UL360Admin.Survey
{
    public partial class SurveyReports : System.Web.UI.Page
    {
        int version = 0;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                //If showing pdf
                if (Request.Form["ShowPdf"] != null)
                {
                    //Get contents of hidden form control where PDF content resides
                    byte[] pdfContent = Convert.FromBase64String(Request.Form["pdfContent"]);
                
                    //Create stream for pdfcontent
                    System.IO.MemoryStream stream = new System.IO.MemoryStream(pdfContent);
                
                    //Create PDF Response
                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-length", stream.Length.ToString());
                    Response.BinaryWrite(stream.ToArray());
                    Response.Flush();
                    stream.Close();
                    Response.End();
                }
                //If showing list
                else
                {   
                    //Set default surveyType
                    SurveyType surveyType = 0;
                    
                    //List to hold survey form versions
                    List<SurveyForm> surveyforms = new List<SurveyForm>();

                    //Get requested surveyType from querystring
                    if (Request.QueryString["FormType"] != null)
                    {
                        int formType = 0;
                        int.TryParse(Request.QueryString["FormType"], out formType);
                        surveyType = (SurveyType)formType;

                        if (surveyType == SurveyType.ExtendedCourse)
                        {
                            ReportListTitle.Text = "Kursutvärderingsrapporter del 2";
                        }

                        //Add survey form id depending on survey type to list
                        using (var db = new UL360Entities())
                        {
                            surveyforms = db.SurveyForms.Where(t => t.SurveyType == (int)surveyType).ToList();
                        }

                        //Add survey form versions to dropdown list
                        if (!Page.IsPostBack)
                        {
                            foreach (SurveyForm form in surveyforms)
                            {
                                SurveyVersions.DataSource = surveyforms;
                                SurveyVersions.DataTextField = "SurveyFormId";
                                SurveyVersions.DataValueField = "SurveyFormId";
                                SurveyVersions.DataBind();
                                SurveyVersions.Items.Insert(0, new ListItem("Visa alla", "0"));
                            }
                        }

                        //Get selected survey version
                        version = Convert.ToInt16(SurveyVersions.SelectedItem.Value);

                        if (version == 0)
                        {
                            CheckBoxState.Value = "0";
                            CompareCourses.Visible = false;
                        }
                        else
                        {
                            CheckBoxState.Value = version.ToString();
                            CompareCourses.Visible = true;
                        }
                    }

                    //Set form type field to survey type
                    FormType.Value = ((int)surveyType).ToString();

                    //Check session sorting and get courses by sorting order
                    if (Session["sortExpression"] != null)
                    {
                        string[] sort = Session["sortExpression"].ToString().Trim().Split(';');
                        bool sortAscending;
                        bool.TryParse(sort[1], out sortAscending);
                        GetCourses(surveyType, sort[0], sortAscending);
                    }
                    else 
                    {
                        GetCourses(surveyType);
                    }
                }

            }
            //If error occured
            catch(Exception exc)
            {
                //Log error
                string errorTicket = UL360SurveyCommon.LoggerCommon.LogNewEntry(
                    new UL360SurveyCommon.LoggerCommon.LogNewEntryDelegate(UL360Admin.Survey.Utils.Logger.LogNewEntry),
                    System.Reflection.MethodBase.GetCurrentMethod().Name, exc.ToString(), (int)UL360SurveyCommon.SurveyLoggingLevel.Error);

                ErrorLabel.Text = "Ett fel uppstod vid hämtning av rapporter, försök igen eller kontakta support med följande ID: " + errorTicket.ToString();
            }
        }

        protected void GetCourses(SurveyType surveyType,  string expression = "slutdatum", bool sortAscending = false)
        {
            List<Kurstillfalle> courses = new List<Kurstillfalle>();

            #region if surveytype is original course (part 1)
            if (surveyType.Equals(SurveyType.OriginalCourse))
            {
                using (var db = new UL360Entities())
                {
                    //Get & set intervals
                    SurveyIntervalSetting intervals = db.SurveyIntervalSettings.First();
                    int totaldays = (intervals.SendSurveyMailInterval * 7) + (intervals.SendReminderMailInterval * 7) + (intervals.LastAnswerInterval * 7);

                    //Get active courses
                    var activeCourses = db.Kurstillfalles.Include("Handledare").Include("Handledares").Where(k => k.aktiv).ToList();

                    //Get courses for selected survey version
                    if (version != 0)
                    {
                        //Get forms from selected survey version and below
                        var form = db.SurveyForms.Where(f => f.SurveyFormId >= version && f.SurveyType == (int)surveyType).OrderByDescending(f => f.SurveyFormId).ToList();

                        //count survey versions
                        int numberOfVersions = form.Count();

                        //Get creation dates for the survey versions
                        //Get courses if several survey forms are available
                        if (numberOfVersions > 1)
                        {
                            //Get form creation dates
                            DateTime date1 = form
                            .Where(f => f.SurveyFormId == version)
                            .OrderByDescending(f => f.SurveyFormId)
                            .First().DateCreated;

                            DateTime date2 = form
                            .Where(f => f.SurveyFormId > version)
                            .OrderByDescending(f => f.SurveyFormId)
                            .First().DateCreated;

                            //Get courses that matches the survey dates
                            activeCourses = activeCourses.Where(c => c.slutdatum >= date1 && c.slutdatum < date2).ToList();
                        }
                        //Get courses if only one survey form is available
                        else
                        {
                            //Get form creation date
                            DateTime date = form.Where(f => f.SurveyFormId == version).First().DateCreated;

                            //Get courses that matches the survey date
                            activeCourses = activeCourses.Where(c => c.slutdatum >= date).ToList();
                        }
                    }

                    #region Order list
                    //Check order and order course by course property
                    //If property to order is not "Handledare"
                    if (expression != "Handledare")
                    {
                        //If descending
                        if (!sortAscending)
                        {
                            activeCourses = activeCourses.OrderByDescending(k => k.GetType().GetProperties().Where(p => p.Name == expression).First().GetValue(k, null)).ToList();
                        }
                        //If ascending
                        else
                        {
                            activeCourses = activeCourses.OrderBy(k => k.GetType().GetProperties().Where(p => p.Name == expression).First().GetValue(k, null)).ToList();
                        }
                    }
                    //If property to order by is "Handledare"
                    else
                    {
                        //If descending
                        if (!sortAscending)
                        {
                            activeCourses = activeCourses.OrderByDescending(k => k.Handledare.fornamn).ToList();
                        }
                        //If ascending
                        else
                        {
                            activeCourses = activeCourses.OrderBy(k => k.Handledare.fornamn).ToList();
                        }
                    }
                    #endregion

                    //Get courses where last answer date has passed
                    foreach (Kurstillfalle course in activeCourses)
                    {
                        DateTime lastAnswerDate = course.slutdatum.AddDays(totaldays);

                        //Get surveymails
                        List<SurveyMailedStatu> surveyMails = db.SurveyMailedStatus.Where(m => m.fk_KursId == course.kursid).ToList();

                        //Set last answerdate from mails sent, i.e. if mail was delayed, set last answer date with regard for this
                        if (surveyMails.Where(m => m.MailType == (int)MailType.ReminderMail).DefaultIfEmpty(null).First() != null)
                        {
                            //If reminder mail was sent, set lastanswerdate to LastAnswerInterval from remindermail
                            lastAnswerDate = surveyMails.Where(m => m.MailType == (int)MailType.ReminderMail).First()
                                .DateSent.AddDays(intervals.LastAnswerInterval * 7);
                        }
                        else if (surveyMails.Where(m => m.MailType == (int)MailType.SurveyMail).DefaultIfEmpty(null).First() != null)
                        {
                            //If surveyMail was sent, set lastanswerdate to SendReminderInterval + LastAnswerInterval from SendSurveyMailInterval
                            lastAnswerDate = surveyMails.Where(m => m.MailType == (int)MailType.SurveyMail).First()
                                .DateSent.AddDays((intervals.SendReminderMailInterval * 7) + (intervals.LastAnswerInterval * 7));
                        }

                        if (lastAnswerDate < DateTime.Now)
                        {
                            courses.Add(course);
                        }
                    }
                }
            }
            #endregion

            #region if surveytype is extended course (part 2)
            else if (surveyType.Equals(SurveyType.ExtendedCourse))
            {
                using (var db = new UL360Entities())
                {
                    //Get & set intervals
                    SurveyIntervalSetting intervals = db.SurveyIntervalSettings.First();
                    int totaldays = (intervals.SendSurveyMailInterval * 7) + (intervals.SendReminderMailInterval * 7) + (intervals.LastAnswerInterval * 7);

                    //Get active courses
                    var activeCourses = db.Kurstillfalles.Include("Handledare").Include("Handledares").Where(k => k.aktiv && k.DatumFordjupningsdag != null).ToList();

                    //Get courses for selected survey version
                    if (version != 0)
                    {
                        //Get forms from selected survey version and below
                        var form = db.SurveyForms.Where(f => f.SurveyFormId >= version && f.SurveyType == (int)surveyType).OrderByDescending(f => f.SurveyFormId).ToList();

                        //count survey versions
                        int numberOfVersions = form.Count();

                        //Get creation dates for the survey versions
                        //Get courses if several survey forms are available
                        if (numberOfVersions > 1)
                        {
                            //Get form creation dates
                            DateTime date1 = form
                            .Where(f => f.SurveyFormId == version)
                            .OrderByDescending(f => f.SurveyFormId)
                            .First().DateCreated;

                            DateTime date2 = form
                            .Where(f => f.SurveyFormId > version)
                            .OrderByDescending(f => f.SurveyFormId)
                            .First().DateCreated;

                            //Get courses that matches the survey dates
                            activeCourses = activeCourses.Where(c => c.slutdatum >= date1 && c.slutdatum < date2).ToList();
                        }
                        //Get courses if only one survey form is available
                        else 
                        {
                            //Get form creation date
                            DateTime date = form.Where(f => f.SurveyFormId == version).First().DateCreated;

                            //Get courses that matches the survey date
                            activeCourses = activeCourses.Where(c => c.slutdatum >= date).ToList();
                        }
                    }

                    #region Order list
                    //Check order and order course by course property
                    //If property to order is not "Handledare"

                    if (expression != "Handledare")
                    {
                        //If descending
                        if (!sortAscending)
                        {
                            activeCourses = activeCourses.OrderByDescending(k => k.GetType().GetProperties().Where(p => p.Name == expression).First().GetValue(k, null)).ToList();
                        }
                        //If ascending
                        else
                        {
                            activeCourses = activeCourses.OrderBy(k => k.GetType().GetProperties().Where(p => p.Name == expression).First().GetValue(k, null)).ToList();
                        }
                    }
                    //If property to order by is "Handledare"
                    else
                    {
                        //If descending
                        if (!sortAscending)
                        {
                            activeCourses = activeCourses.OrderByDescending(k => k.Handledare.fornamn).ToList();
                        }
                        //If ascending
                        else
                        {
                            activeCourses = activeCourses.OrderBy(k => k.Handledare.fornamn).ToList();
                        }
                    }                    
                    #endregion

                    //Get courses where last answer date has passed
                    if (activeCourses.Count > 0)
                    {
                        foreach (Kurstillfalle course in activeCourses)
                        {
                            if (course.DatumFordjupningsdag != null && ((DateTime)course.DatumFordjupningsdag) < DateTime.Now)
                            {
                                //Add days to fordjupningsdag to get the last answerdate for the part 2 survey
                                DateTime lastAnswerDate = ((DateTime)course.DatumFordjupningsdag).AddDays(totaldays);
                                
                                //Get surveymails
                                List<SurveyMailedStatu> surveyMails = db.SurveyMailedStatus.Where(m => m.fk_KursId == course.kursid).ToList();

                                //Set last answerdate from mails sent, i.e. if mail was delayed, set last answer date with regard for this
                                if (surveyMails.Where(m => m.MailType == (int)MailType.ExtReminderMail).DefaultIfEmpty(null).First() != null)
                                {
                                    //If reminder mail was sent, set lastanswerdate to LastAnswerInterval from remindermail
                                    lastAnswerDate = surveyMails.Where(m => m.MailType == (int)MailType.ExtReminderMail).First()
                                        .DateSent.AddDays(intervals.LastAnswerInterval * 7);
                                }
                                else if (surveyMails.Where(m => m.MailType == (int)MailType.ExtSurveyMail).DefaultIfEmpty(null).First() != null)
                                {
                                    //If surveyMail was sent, set lastanswerdate to SendReminderInterval + LastAnswerInterval from SendSurveyMailInterval
                                    lastAnswerDate = surveyMails.Where(m => m.MailType == (int)MailType.ExtSurveyMail).First()
                                        .DateSent.AddDays((intervals.SendReminderMailInterval * 7) + (intervals.LastAnswerInterval * 7));
                                }

                                if (lastAnswerDate < DateTime.Now)
                                {
                                    //Add course to the list courses
                                    courses.Add(course);
                                }
                            }
                        }
                    }
                    else 
                    {
                        courses.Clear();
                    }
                }
            }
            #endregion

            //Set current order of listview
            Session["sortExpression"] = expression + ";" + sortAscending.ToString();

            if (courses.Count > 0)
            {
                InformationLabel.Text = "";

                //Load list with courses that matches the criteria (dates, surveytype and surveyversion)
                ReportsListView.DataSource = courses;
                ReportsListView.DataBind();


                #region If the list is for original courses
                if (surveyType.Equals(SurveyType.OriginalCourse))
                {
                    ReportsListView.FindControl("SortByExtDate").Visible = false;
                    ReportsListView.FindControl("SortByEndDate").Visible = true;

                    foreach (ListViewItem item in ReportsListView.Items)
                    {
                        int courseId = Convert.ToInt32(((HiddenField)item.FindControl("courseId")).Value);
                        Handledare mainTutor = courses.Where(c => c.kursid == courseId).DefaultIfEmpty(null).First().Handledare;
                        List<Handledare> tutors = courses.Where(c => c.kursid == courseId).First().Handledares.ToList();
                        Kurstillfalle course;

                        #region get answer values from scale questions for course
                        //Variables to hold answer values
                        int formId;
                        ICollection<SurveyQuestionText> scaleQuestionTexts;
                        ICollection<SurveyAnswerScale> scaleAnswers;
                        List<double> totalValue = new List<double>();
                        double courseTotalAverage;

                        //Get survey form and scale answers for the course and form
                        using (var db = new UL360Entities())
                        {
                            //Get course
                            course = db.Kurstillfalles.Include("Handledares").Include("Handledare").Where(c => c.kursid == courseId).DefaultIfEmpty(null).First();

                            //Get survey form for course
                            formId = db.SurveyForms.Where(f => f.SurveyType == (int)surveyType && f.DateCreated <= course.slutdatum).OrderByDescending(f => f.DateCreated).First().SurveyFormId;
                            
                            //Get questions texts for form id and question type
                            scaleQuestionTexts = db.SurveyForms.Where(f => f.SurveyFormId == formId).SelectMany(fq => fq.SurveyQuestions).OrderBy(q => q.Order).Where(type => type.QuestionType == 0).SelectMany(qt => qt.SurveyQuestionTexts).Where(l => l.fk_SprakId == 1).ToList();
                            
                            //Get scale answers by course and form id
                            scaleAnswers = course.SurveyAnswerScales.Where(q => q.fk_SurveyFormId == formId && q.fk_KursId == courseId).ToList();
                        }

                        //Get question texts and answers for each question
                        foreach (SurveyQuestionText question in scaleQuestionTexts)
                        {
                            List<int> answerValues = new List<int>();

                            if (scaleAnswers.Count > 0)
                            {
                                //Get all answer values for the specific question
                                foreach (var answer in scaleAnswers.Where(sq => sq.fk_SurveyQuestionId == question.fk_SurveyQuestionId).ToList())
                                {
                                    answerValues.Add(answer.ScaleAnswer);
                                }
                            }

                            //Add answer values that are not equal to zero
                            answerValues = answerValues.Where(a => a != 0).ToList();

                            //Number of answers
                            double length = answerValues.Count();

                            //Sum of all answer values for the question
                            double sum = answerValues.Sum();

                            //Set number of answerers and average value for this question
                            double average = sum / length;

                            //If all anwers was "dont know"
                            if (double.IsNaN(average))
                            {
                                average = 0;
                            }

                            //Add average value of all answers for this question
                            totalValue.Add(average);
                        }

                        //Get course total average value
                        courseTotalAverage = Math.Round(totalValue.Sum() / scaleQuestionTexts.Count, 2);
                        #endregion

                        //Show course end date in list
                        ((Label)item.FindControl("endDate")).Text = courses.Where(c => c.kursid == courseId).First().slutdatum.ToString("yyyy-MM-dd");

                        //Set average value for course if the value is not zero
                        if (courseTotalAverage.ToString() != "0")
                        {
                            ((Label)item.FindControl("average")).Text = courseTotalAverage.ToString();
                        }
                        else
                        {
                            ((Label)item.FindControl("average")).Text = "Inga svar";
                        }

                        //Show tutors for the course in list
                        if (mainTutor != null)
                        {
                            ((Label)item.FindControl("mainTutor")).Text = mainTutor.fornamn + " " + mainTutor.efternamn;
                            ((Label)item.FindControl("tutors")).Text = string.Join(", ", tutors.Where(h => h.handledarid != mainTutor.handledarid).Select(t => t.fornamn + " " + t.efternamn).ToArray());
                        }
                        else
                        {
                            ((Label)item.FindControl("tutors")).Text = string.Join(", ", tutors.Select(t => t.fornamn + " " + t.efternamn).ToArray());
                        }
                    }
                }
                #endregion
                
                #region If the list is for extended courses
                else if (surveyType.Equals(SurveyType.ExtendedCourse))
                {
                    ReportsListView.FindControl("SortByEndDate").Visible = false;
                    ReportsListView.FindControl("SortByExtDate").Visible = true;

                    foreach (ListViewItem item in ReportsListView.Items)
                    {
                        int courseId = Convert.ToInt32(((HiddenField)item.FindControl("courseId")).Value);
                        Handledare mainTutor = courses.Where(c => c.kursid == courseId).DefaultIfEmpty(null).First().Handledare;
                        List<Handledare> tutors = courses.Where(c => c.kursid == courseId).First().Handledares.ToList();
                        Kurstillfalle course;

                        #region get answer values from scale questions for course
                        //Variables to hold answer values
                        int formId;
                        ICollection<SurveyQuestionText> scaleQuestionTexts;
                        ICollection<SurveyAnswerScale> scaleAnswers;
                        List<double> totalValue = new List<double>();
                        double courseTotalAverage;

                        //Get survey form and scale answers for the course and form
                        using (var db = new UL360Entities())
                        {
                            //Get course
                            course = db.Kurstillfalles.Include("Handledares").Include("Handledare").Where(c => c.kursid == courseId).DefaultIfEmpty(null).First();

                            //Get survey form for course
                            formId = db.SurveyForms.Where(f => f.SurveyType == (int)surveyType && f.DateCreated <= course.slutdatum).OrderByDescending(f => f.DateCreated).First().SurveyFormId;

                            //Get questions texts for form id and question type
                            scaleQuestionTexts = db.SurveyForms.Where(f => f.SurveyFormId == formId).SelectMany(fq => fq.SurveyQuestions).OrderBy(q => q.Order).Where(type => type.QuestionType == 0).SelectMany(qt => qt.SurveyQuestionTexts).Where(l => l.fk_SprakId == 1).ToList();

                            //Get scale answers by course and form id
                            scaleAnswers = course.SurveyAnswerScales.Where(q => q.fk_SurveyFormId == formId && q.fk_KursId == courseId).ToList();
                        }

                        //Get question texts and answers for each question
                        foreach (SurveyQuestionText question in scaleQuestionTexts)
                        {
                            List<int> answerValues = new List<int>();

                            if (scaleAnswers.Count > 0)
                            {
                                //Get all answer values for the specific question
                                foreach (var answer in scaleAnswers.Where(sq => sq.fk_SurveyQuestionId == question.fk_SurveyQuestionId).ToList())
                                {
                                    answerValues.Add(answer.ScaleAnswer);
                                }
                            }

                            //Add answer values that are not equal to zero
                            answerValues = answerValues.Where(a => a != 0).ToList();

                            //Number of answers
                            double length = answerValues.Count();

                            //Sum of all answer values for the question
                            double sum = answerValues.Sum();

                            //Set number of answerers and average value for this question
                            double average = sum / length;

                            //If all anwers was "dont know"
                            if (double.IsNaN(average))
                            {
                                average = 0;
                            }

                            //Add average value of all answers for this question
                            totalValue.Add(average);
                        }

                        //Get course total average value
                        courseTotalAverage = Math.Round(totalValue.Sum() / scaleQuestionTexts.Count, 2);
                        #endregion

                        ((Label)item.FindControl("endDate")).Text = ((DateTime)courses.Where(c => c.kursid == courseId).First().DatumFordjupningsdag).ToString("yyyy-MM-dd");

                        //Set average value for course if the value is not zero
                        if (courseTotalAverage.ToString() != "0")
                        {
                            ((Label)item.FindControl("average")).Text = courseTotalAverage.ToString();
                        }
                        else
                        {
                            ((Label)item.FindControl("average")).Text = "Inga svar";
                        }

                        if (mainTutor != null)
                        {
                            ((Label)item.FindControl("mainTutor")).Text = mainTutor.fornamn + " " + mainTutor.efternamn;
                            ((Label)item.FindControl("tutors")).Text = string.Join(", ", tutors.Where(h => h.handledarid != mainTutor.handledarid).Select(t => t.fornamn + " " + t.efternamn).ToArray());
                        }
                        else
                        {
                            ((Label)item.FindControl("tutors")).Text = string.Join(", ", tutors.Select(t => t.fornamn + " " + t.efternamn).ToArray());
                        }
                    }
                }
                #endregion
            }
                //If there are not any courses available that matches the dates
            else
            {
                if (courses.Count == 0 && version != 0)
                {
                    InformationLabel.Text = "Det finns inga rapporter tillgängliga för denna enkätversion";

                    CompareCourses.Visible = false;

                    ReportsListView.DataSource = courses;
                    ReportsListView.DataBind();
                }
                else
                {
                    InformationLabel.Text = "Det finns inga rapporter tillgängliga";
                }
            }
        }

        #region Sorting report list
        //Sort list with reports
        protected void ReportsListView_Sorting(object sender, CommandEventArgs e)
        {
            try
            {
                //Get and set sort expression and order
                string expression = e.CommandArgument.ToString();
                string[] sort = Session["sortExpression"].ToString().Trim().Split(';');
                bool sortAscending;
                bool.TryParse(sort[1], out sortAscending);

                //Set sorting order
                if (sortAscending)
                {
                    sortAscending = false;
                }
                else
                {
                    sortAscending = true;
                }

                //Convert form type
                int formType = Convert.ToInt16(FormType.Value);

                //Set order on active courses
                GetCourses((SurveyType)formType, expression, sortAscending);
            }
            //If error occured
            catch (Exception exc)
            {
                //Log error
                string errorTicket = UL360SurveyCommon.LoggerCommon.LogNewEntry(
                    new UL360SurveyCommon.LoggerCommon.LogNewEntryDelegate(UL360Admin.Survey.Utils.Logger.LogNewEntry),
                    System.Reflection.MethodBase.GetCurrentMethod().Name, exc.ToString(), (int)UL360SurveyCommon.SurveyLoggingLevel.Error);

                ErrorLabel.Text = "Ett fel uppstod vid hämtning av rapporter, försök igen eller kontakta support med följande ID: " + errorTicket.ToString();
            }
        }
        #endregion

        #region Checkboxes in report list
        //Checkboxes to compare reports (Check/uncheck all checkboxes)
        protected void CheckAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox CheckAll = sender as CheckBox;

            if (CheckAll.Checked)
            {
                foreach (ListViewDataItem l in ReportsListView.Items)
                {
                    CheckBox chk = (CheckBox)l.FindControl("CheckBox");
                    chk.Checked = true;
                }
            }
            else
            {
                foreach (ListViewDataItem l in ReportsListView.Items)
                {
                    CheckBox chk = (CheckBox)l.FindControl("CheckBox");
                    chk.Checked = false;
                }
            }

            CheckAll.AutoPostBack = true;
        }
        #endregion

        #region Check courses to compare and create comparison pdf
        //Check which courses to compare (that are checked) and get their values
        protected void CompareCourses_Click(object sender, EventArgs e)
        {
            List<Models.PDFCompareCourses> CoursesToCompare = new List<Models.PDFCompareCourses>();

            foreach (ListViewDataItem item in ReportsListView.Items)
            {
                CheckBox chk = (CheckBox)item.FindControl("CheckBox");

                if (chk.Checked)
                {
                    //Set checked to true when loading page again
                    chk.Checked = true;

                    //Add to list
                    CoursesToCompare.Add(new Models.PDFCompareCourses()
                    {
                        //Get course id
                        CourseID = ((HiddenField)item.FindControl("courseId")).Value,
                        //Get course average value and add to list
                        CourseAverage = ((Label)item.FindControl("average")).Text,
                        //Get survey form id for the course
                        SurveyFormID = SurveyVersions.SelectedItem.Value,
                        //Get survey type
                        SurveyType = Request.QueryString["FormType"]
                    });
                }
            }

            //Call create pdf for comparing courses method and send CoursesToCompare into the method
            if (CoursesToCompare.Count > 0)
            {
                Utils.ReportsUtil.CreateComparePDF(CoursesToCompare);
            }
            else
            {
                ErrorLabel.Text = "Du har inte valt några kurser att jämföra, kryssa i kurser för att kunna jämföra dem med varandra.";
            }
        }
        #endregion

    }
}